//
//  CourseSearchViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/10/12.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "CourseSearchViewController.h"
#import "CourseModel.h"

#import "CourseDetailViewController.h"
#import "AllHeader.h"

#define  sCUrl @"http://arts1.dlab.com.cn/app/course"
//#define  sCUrl @"http://arts1.cn/app/course"


@interface CourseSearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

// 搜索框
@property (nonatomic, strong) UISearchBar *searchBar;

// 搜索参数--- 搜索框输入的信息
@property (nonatomic, strong) NSString *search;

// 搜索得到的数据
@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation CourseSearchViewController

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    return _dataArr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self createSearchbar];
    [self createSearchResultView];
    
}
/**
 *  创建搜索框
 */
- (void)createSearchbar{
    _searchBar = [[UISearchBar alloc] init];
    [_searchBar setFrame:(CGRectMake(2, 25, SCREEN_WIDTH - 4, 34))];
    _searchBar.searchBarStyle = UISearchBarStyleDefault;
    _searchBar.placeholder = @"search";
    _searchBar.delegate = self;
    _searchBar.showsCancelButton = NO;
    
    // UISearchBar 有两个的子视图有两个姿势图，一个是背景视图，一个是textfield
    [self.view addSubview:_searchBar];
    UIView *view = _searchBar.subviews[0];
    [view.subviews[0] removeFromSuperview];
    UITextField *textfield = (UITextField *)view.subviews[0];
    textfield.backgroundColor = kCustomColor(230, 230, 230, 1);
    
}

// 网络请求
- (void)requestSearchResults{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *paraDic = @{@"search":_search};
    
    [manage POST:sCUrl parameters:paraDic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         //返回的状态
         int index = [dic[@"status"] intValue];
         if (index == 1) {
             NSArray *arr = dic[@"list"];
        for (NSDictionary *dict in arr) {
           CourseModel *model = [[CourseModel alloc] init];
           [model setValuesForKeysWithDictionary:dict];
           [self.dataArr addObject:model];
            }
         }  else {
             [MBProgressHUD show:@"请输入正确的课程名称" icon:nil view:self.view];
         
         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.resultView reloadData];
         });
         
         NSLog(@"课程分类返回数据 ： %@", dic);
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
    
}

// 创建搜索结果展示视图
- (void)createSearchResultView{
    _resultView = [[UITableView alloc] initWithFrame:CGRectMake(0,SCREEN_WIDTH, 64, 0) style:(UITableViewStylePlain)];
    _resultView.delegate = self;
    _resultView.dataSource = self;
    [self.view addSubview:_resultView];
}

#pragma mark --- UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.view.frame = CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _resultView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    _searchBar.showsCancelButton = YES;
    return YES;
}

/**
 *  点击搜索   请求搜索结果
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    _search = searchBar.text;
    [self requestSearchResults];
}

/**
 *  取消搜索
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self hideResultsView];
}

- (void)hideResultsView{
    _dataArr = nil;
    _searchBar.showsCancelButton = YES;
    [_searchBar resignFirstResponder];
    _searchBar.text = nil;
    [_resultView reloadData];
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
    _resultView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 0);
}

# pragma mark ---- UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCourse"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"SearchCourse"];
    }
    CourseModel *model = (CourseModel *)_dataArr[indexPath.row];
    cell.textLabel.text = model.title;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseModel *model = (CourseModel *)_dataArr[indexPath.row];
    if (_showSearchBlock) {
        _showSearchBlock(model);
    }
    [self hideResultsView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
